import 'dart:convert';

import 'package:enterprise_v8/app/components/custom_qr_scan.dart';
import 'package:enterprise_v8/app/components/toast_widget.dart';
import 'package:enterprise_v8/app/core/core.dart';
import 'package:enterprise_v8/app/core/utils/log_util.dart';

/// 扫码工具类
class ScanUtil {
  /// 扫描单元上二维码
  /// 返回数据map
  static Future<Map<String, dynamic>> scanUnitQRReturnMap() async {
    String qRCode = '';
    await Get.to(() {
      return CustomQrScanPage(
        onScanResult: (value) {
          try {
            final String str = _decrypt(value);
            qRCode = str;
          } catch (e) {
            AppLogger.printLog(e.toString());
          }
        },
      );
    });
    if (qRCode == '') {
      AppToast.showWarning('请扫描指定二维码');
      return {};
    }
    final Map<String, dynamic> parsedData = parseCustomString(qRCode);
    try {
      parsedData['ID'] as String;
    } catch (e) {
      AppToast.showWarning('解析二维码失败！');
    }
    return parsedData;
  }

  /// 解密
  static String _decrypt(String str) {
    const d = 5197;
    const n = 31439;

    if (str.endsWith(',')) {
      str = str.substring(0, str.length - 1);
    }
    final c = List<int>.from(json.decode('[$str]') as List);
    var temp = 1;
    final decryptedPlain = List.generate(c.length, (index) => 0, growable: false);

    for (int i = 0; i < c.length; i++) {
      for (int j = 0; j < d; j++) {
        temp = temp * c[i] % n;
      }
      decryptedPlain[i] = temp;
      temp = 1;
    }

    return String.fromCharCodes(decryptedPlain);
  }

  static Map<String, dynamic> parseCustomString(String input) {
    final List<String> parts = input.split(',');

    final Map<String, dynamic> data = {};

    for (String part in parts) {
      final List<String> keyValue = part.split(':');
      if (keyValue.length == 2) {
        String key = keyValue[0];
        dynamic value = keyValue[1];

        // 去除可能存在的空格
        key = key.trim();
        value = value.trim();

        data[key] = value;
      }
    }

    return data;
  }

  /// 扫描数据返回
  static Future<String> scanQROrBarCode() async {
    String qRCode = '';
    await Get.to(() {
      return CustomQrScanPage(
        onScanResult: (value) {
          try {
            qRCode = value;
          } catch (e) {
            AppLogger.printLog(e.toString());
          }
        },
      );
    });
    return qRCode;
  }
}
